/*
 * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details.
 */

package at.bitfire.davdroid.webdav

import at.bitfire.davdroid.network.HttpClientBuilder
import at.bitfire.davdroid.network.MemoryCookieStore
import okhttp3.CookieJar
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import javax.inject.Inject
import javax.inject.Provider

class DavHttpClientBuilder @Inject constructor(
    private val credentialsStore: CredentialsStore,
    private val httpClientBuilder: Provider<HttpClientBuilder>,
) {

    /**
     * Creates an HTTP client that can be used to access resources in the given mount.
     *
     * @param mountId    ID of the mount to access
     * @param logBody    whether to log the body of HTTP requests (disable for potentially large files)
     */
    fun build(mountId: Long, logBody: Boolean = true): OkHttpClient {
        val cookieStore = cookieStores.getOrPut(mountId) {
            MemoryCookieStore()
        }
        val builder = httpClientBuilder.get()
            .loggerInterceptorLevel(if (logBody) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.HEADERS)
            .setCookieStore(cookieStore)

        credentialsStore.getCredentials(mountId)?.let { credentials ->
            builder.authenticate(
                domain = null,
                getCredentials = { credentials }
            )
        }

        return builder.build()
    }


    companion object {

        /** in-memory cookie stores (one per mount ID) that are available until the content
         * provider (= process) is terminated */
        private val cookieStores = mutableMapOf<Long, CookieJar>()

    }

}